package com.jxwifi.cloud.quickcleanserver.mycenter;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.basicactivity.BasicActivity;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.idroid.widget.LoadDialog;
import com.jxwifi.cloud.quickcleanserver.R;
import com.jxwifi.cloud.quickcleanserver.adapter.MyLinearLayoutManager;
import com.jxwifi.cloud.quickcleanserver.adapter.PriceDetailedListAdapter;
import com.jxwifi.cloud.quickcleanserver.app.AccountMgr;
import com.jxwifi.cloud.quickcleanserver.app.CleanBasicActivity;
import com.jxwifi.cloud.quickcleanserver.app.UrlPool;
import com.jxwifi.cloud.quickcleanserver.bean.InfoBean;
import com.jxwifi.cloud.quickcleanserver.bean.RecordsBean;
import com.jxwifi.cloud.quickcleanserver.bean.SystemBean;
import com.jxwifi.cloud.quickcleanserver.bean.WithdraApplyBean;
import com.jxwifi.cloud.quickcleanserver.okhttp.AuzHttp;
import com.jxwifi.cloud.quickcleanserver.okhttp.DataJson_Cb;
import com.jxwifi.cloud.quickcleanserver.okhttp.Params;
import com.jxwifi.cloud.quickcleanserver.presenter.MyBalancePresenter;
import com.jxwifi.cloud.quickcleanserver.utils.PasswordLogin;
import com.jxwifi.cloud.quickcleanserver.utils.ToastUtils;
import com.jxwifi.cloud.quickcleanserver.view.MyBalanceView;

import java.io.Serializable;
import java.util.Calendar;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.trinea.android.common.util.ListUtils;

/**
 * 我的余额
 * Created by Administrator on 2019/5/14.
 */

public class MyBalanceActivity extends CleanBasicActivity implements MyBalanceView {


    private String TAG = this.getClass().getSimpleName();
    public static int PAGE_SIZE = 10;
    @Bind(R.id.img_back_pressed)
    ImageView mImgBackPrice;
    @Bind(R.id.tv_my_balance_price)
    TextView mTvMyBalancePrice;//余额
    @Bind(R.id.srl_fg_my_balance_list)
    SwipeRefreshLayout mSrlFgMyBalanceList;
    @Bind(R.id.rv_my_balance_list)
    RecyclerView mRvMyBalanceList;
    @Bind(R.id.rel_null_data)
    RelativeLayout mrel_nulldata;

    private PriceDetailedListAdapter mAdapter;
    private int mPageIndex = 1;//页数
    private int mTotalNum;//记录接口中的总条数（如果没有返回这个字段也可以不适用）

    private boolean isErr = true;

    private String mReturnData;
    private int mCurrentCounter;//获取的数据个数
    private boolean mNoData = true;
    private View notDataView;

    private MyBalancePresenter myBalancePresenter;
    private LoadDialog mLoadDialog;

    //private ArrayList<RecordsBean> mList=new ArrayList<>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_balance);
        ButterKnife.bind(this);
        openEventBus();
        myBalancePresenter = new MyBalancePresenter(this);
        initRefreshLayout();
        mLoadDialog= new LoadDialog(mBaseContext, "");
    }

    public void initView() {
        mTvMyBalancePrice.setText("" + AccountMgr.getamount(mBaseContext));
        mRvMyBalanceList.setLayoutManager(new MyLinearLayoutManager(mBaseContext));
        mRvMyBalanceList.setAdapter(mAdapter = new PriceDetailedListAdapter(R.layout.list_my_balance_item));

        mAdapter.openLoadAnimation();
        mAdapter.openLoadAnimation(BaseQuickAdapter.FOOTER_VIEW);

        //上拉加载更多操作
        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                mRvMyBalanceList.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (mCurrentCounter >= mTotalNum) {
                            //数据全部加载完毕
                            mAdapter.loadMoreEnd();
                        } else {
                            if (isErr) {
                                onLoadMore();
                                //成功获取更多数据
                                mCurrentCounter = mAdapter.getData().size();
                                mAdapter.loadMoreComplete();
                            } else {
                                //获取更多数据失败
                                isErr = true;
                                Toast.makeText(mBaseContext, "获取更多数据失败", Toast.LENGTH_LONG).show();
                                mAdapter.loadMoreFail();
                            }
                        }
                    }
                }, 1500);

            }
        }, mRvMyBalanceList);

        notDataView = getLayoutInflater().inflate(R.layout.null_layout, (ViewGroup) mRvMyBalanceList.getParent(), false);
        notDataView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Refresh();
            }
        });
    }

    private void initRefreshLayout() {
        mSrlFgMyBalanceList.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Refresh();
            }
        });
    }

    @OnClick({R.id.tv_my_balance_cash_withdrawal, R.id.rel_img_back_pressed})
    void clickCK(View v) {
        switch (v.getId()) {
            //提现
            case R.id.tv_my_balance_cash_withdrawal:

                mLoadDialog.show();

                myBalancePresenter.doinitleaves();//提现的限制条件


                break;
            case R.id.rel_img_back_pressed:
                onBackPressed();
                break;
        }
    }

    public void Refresh() {
        mAdapter.setEmptyView(R.layout.loading_view, (ViewGroup) mRvMyBalanceList.getParent());
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (mNoData) {
                    myBalancePresenter.domemberinfo();
                    mPageIndex = 1;
                    myBalancePresenter.doList();
                } else {
                    mAdapter.setEmptyView(notDataView);
                }
            }
        }, 1000);
    }

    private void onLoadMore() {
        myBalancePresenter.doList();
    }

    public int getPageIndex() {
        return mPageIndex;
    }

    public int getPAGE_SIZE() {
        return PAGE_SIZE;
    }

    public int getCurrentCounter() {
        return mCurrentCounter;
    }

    @Override
    public boolean getNoData() {
        return mNoData;
    }

    @Override
    public String getReturnData() {
        return mReturnData;
    }

    @Override
    public void getListonSuccess(int code, String data) {
        mSrlFgMyBalanceList.setRefreshing(false);
        if (code == 0) {
            JSONObject obj = JSON.parseObject(data);
            String str = obj.getString("records");
            mTotalNum = obj.getInteger("total");
            List<RecordsBean> mrecords = JSON.parseArray(str, RecordsBean.class);
            if (mPageIndex == 1) {
                setData(true, mrecords);
            } else {

                setData(false, mrecords);
            }
        } else {
            PasswordLogin.passwordlogin(mBaseContext, TAG, AccountMgr.gettell(mBaseContext), AccountMgr.getpassword(mBaseContext));
            if (PasswordLogin.mIsLogin) {
                myBalancePresenter.doList();
            }
        }
    }

    @Override
    public void getListonFailure(int errorCode, String msg) {
        isErr = false;
        mSrlFgMyBalanceList.setRefreshing(false);
        Toast toast = Toast.makeText(mBaseContext, msg, Toast.LENGTH_SHORT);
        ToastUtils.showMyToast(toast, 3000);
    }

    @Override
    public void initleavesonSuccess(int code, String data) {
        if (code == 0) {//正常数据
            List<SystemBean> msystemBean = JSON.parseArray(data, SystemBean.class);
            for (int i = 0; i < msystemBean.size(); i++) {
                if ("kjb_cleaner_cashout".equals(msystemBean.get(i).getKeyName())) {
                    mReturnData = msystemBean.get(i).getKeyValue();
                    break;
                }
            }
            Calendar calendar = Calendar.getInstance();
            String mday;
            if (calendar.get(Calendar.DAY_OF_MONTH) < 10) {
                mday = "0" + calendar.get(Calendar.DAY_OF_MONTH);
            } else {
                mday = "" + calendar.get(Calendar.DAY_OF_MONTH);
            }
            if (mReturnData.indexOf(mday) != -1) { //表示包含这个字段
                if (Double.valueOf(AccountMgr.getamount(mBaseContext)) >= 10) {
                    if(myBalancePresenter.mListBean.size() == 0){
                        Intent intent = new Intent(mBaseContext, AddCardActivity.class);
                        intent.putExtra("flag",1);
                        //intent.putExtra("list", (Serializable) mListBean);
                        startActivity(intent);
                    }else {
                        Intent intent = new Intent();
                        intent.putExtra("list", (Serializable) myBalancePresenter.mListBean);
                        intent.setClass(mBaseContext, WithdrawalActivity.class);
                        startActivity(intent);
                    }
                } else {
                    if (Double.valueOf(AccountMgr.getamount(mBaseContext)) == 0.0) {
                        Toast toast = Toast.makeText(mBaseContext, "暂无金额不可提现", Toast.LENGTH_SHORT);
                        ToastUtils.showMyToast(toast, 3000);
                    } else {
                        Toast toast = Toast.makeText(mBaseContext, "提现金额小于10元，不可提现", Toast.LENGTH_SHORT);
                        ToastUtils.showMyToast(toast, 3000);
                    }
                }

            } else {
                Toast toast = Toast.makeText(mBaseContext, "提现日期为" + mReturnData + "日", Toast.LENGTH_SHORT);
                ToastUtils.showMyToast(toast, 3000);
            }

        } else {//请他情况做密码登录接口请求操作后再次请求接口
            PasswordLogin.passwordlogin(mBaseContext, TAG, AccountMgr.gettell(mBaseContext), AccountMgr.getpassword(mBaseContext));
            if (PasswordLogin.mIsLogin) {
                myBalancePresenter.doinitleaves();
            }
        }
    }

    @Override
    public void initleavesonFailure(int errorCode, String msg) {
        Toast toast = Toast.makeText(mBaseContext, msg, Toast.LENGTH_SHORT);
        ToastUtils.showMyToast(toast, 3000);
    }

    @Override
    public void memberinfoonSuccess(int code, String data) {
        if (code == 0) {//正常数据
            InfoBean mInfoBean = JSON.parseObject(data, InfoBean.class);
            AccountMgr.putUser(mBaseContext, mInfoBean, false);
            mTvMyBalancePrice.setText("" + AccountMgr.getamount(mBaseContext));
            Log.w("OSH", "memberinfo");
        } else {//请他情况做密码登录接口请求操作后再次请求接口
            PasswordLogin.passwordlogin(mBaseContext, TAG, AccountMgr.gettell(mBaseContext), AccountMgr.getpassword(mBaseContext));
            if (PasswordLogin.mIsLogin) {
                myBalancePresenter.domemberinfo();
            }
        }
    }

    @Override
    public void memberinfoonFailure(int errorCode, String msg) {
        Toast toast = Toast.makeText(mBaseContext, msg, Toast.LENGTH_SHORT);
        ToastUtils.showMyToast(toast, 3000);
    }

    @Override
    public void dissDialog() {
        mLoadDialog.dismiss();
    }

    public void setData(boolean isRefresh, List data) {
        mPageIndex++;
        final int size = data == null ? 0 : data.size();
        if (isRefresh) {
            if (data == null || data.size() == 0) {
                mNoData = false;
                mAdapter.setEmptyView(notDataView);
            } else {
                mAdapter.setNewData(data);
            }
        } else {
            if (size > 0) {
                mAdapter.addData(data);
            }
        }
        mCurrentCounter = mAdapter.getData().size();
        if (size < PAGE_SIZE) {
            //第一页如果不够一页就不显示没有更多数据布局
            mAdapter.loadMoreEnd(isRefresh);
        } else {
            mAdapter.loadMoreComplete();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        initView();
        Refresh();
    }

}
